//
//  LoginViewController.m
//  ChatDemo
//
//  Created by imac on 15/12/20.
//  Copyright © 2015年 imac. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;


@property (weak, nonatomic) IBOutlet UIButton *doRegister;
@property (weak, nonatomic) IBOutlet UIButton *doLogin;

- (IBAction)doRegister:(id)sender;
- (IBAction)doLogin:(id)sender;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setInutStyle:self.usernameTextField imgName:@"login_user"];
    [self setInutStyle:self.passwordTextField imgName:@"login_mima"];
    self.doRegister.layer.cornerRadius = 2;
    self.doLogin.layer.cornerRadius = 2;
}

-(void)setInutStyle:(UITextField *)textfield imgName:(NSString *)imgName{
    UIView *userNameLeftView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, 40, 40)];
    UIImageView *img = [[UIImageView alloc ] initWithFrame:CGRectMake(10, 10, 18, 18)];
    img.image = [UIImage imageNamed:imgName];
    [userNameLeftView addSubview:img];
    textfield.leftView = userNameLeftView;
    textfield.leftViewMode = UITextFieldViewModeAlways;
    textfield.layer.cornerRadius = 2;

}

- (IBAction)doRegister:(id)sender{
    
    [self.view endEditing:YES];
    
    [self showHudInView:self.view hint:NSLocalizedString(@"register.ongoing", @"Is to register...")];
    //异步注册账号
    [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:_usernameTextField.text
                                                         password:_passwordTextField.text
                                                   withCompletion:
     ^(NSString *username, NSString *password, EMError *error) {
         [self hideHud];
         
         if (!error) {
             TTAlertNoTitle(NSLocalizedString(@"register.success", @"Registered successfully, please log in"));
         }else{
             switch (error.errorCode) {
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                     break;
                 case EMErrorServerDuplicatedAccount:
                     TTAlertNoTitle(NSLocalizedString(@"register.repeat", @"You registered user already exists!"));
                     break;
                 case EMErrorNetworkNotConnected:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                     break;
                 default:
                     TTAlertNoTitle(NSLocalizedString(@"register.fail", @"Registration failed"));
                     break;
             }
         }
     } onQueue:nil];
}

//登陆账号
- (IBAction)doLogin:(id)sender {
    
    [self.view endEditing:YES];
    
    [self loginWithUsername:_usernameTextField.text password:_passwordTextField.text];
    
}

//点击登陆后的操作
- (void)loginWithUsername:(NSString *)username password:(NSString *)password
{
    [self showHudInView:self.view hint:NSLocalizedString(@"login.ongoing", @"Is Login...")];
    //异步登陆账号
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:username
                                                        password:password
                                                      completion:
     ^(NSDictionary *loginInfo, EMError *error) {
         [self hideHud];
         if (loginInfo && !error) {
             
             //设置是否自动登录
             [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
            
             //获取数据库中数据
             [[EaseMob sharedInstance].chatManager loadDataFromDatabase];
             
             //保存最近一次登录用户名
             [self saveLastLoginUsername];
        
             //发送自动登陆状态通知
             [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
            
         }
         else
         {
             switch (error.errorCode)
             {
                 case EMErrorNotFound:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorNetworkNotConnected:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectNetworkFail", @"No network connection!"));
                     break;
                 case EMErrorServerNotReachable:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerFail", @"Connect to the server failed!"));
                     break;
                 case EMErrorServerAuthenticationFailure:
                     TTAlertNoTitle(error.description);
                     break;
                 case EMErrorServerTimeout:
                     TTAlertNoTitle(NSLocalizedString(@"error.connectServerTimeout", @"Connect to the server timed out!"));
                     break;
                 default:
                     TTAlertNoTitle(NSLocalizedString(@"login.fail", @"Login failure"));
                     break;
             }
         }
     } onQueue:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma  mark - private
- (void)saveLastLoginUsername
{
    NSString *username = [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:kSDKUsername];
    if (username && username.length > 0) {
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:username forKey:[NSString stringWithFormat:@"em_lastLogin_%@",kSDKUsername]];
        [ud synchronize];
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
